package com.lefu.es.blenew.service;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.lefu.es.blenew.bean.BleAdvertisedData1;
import com.lefu.es.blenew.bean.BluetoothLeDevice1;
import com.lefu.es.blenew.constant.BluetoolUtil1;
import com.lefu.es.blenew.utils.BleUtil1;
import com.lefu.es.blenew.utils.StringUtils1;
import com.lefu.es.constant.AppData;
import com.lefu.es.util.LogUtil;
import com.lefu.es.util.StringUtils;


/**
 * 作者: andy on 2016/11/9.
 * 作用: 4.3 版本以上，5.0版本以下的系统
 */
public class BluetoothLeScanner extends BluetoothLeScannerInterface {

    private final BluetoothUtils1 mBluetoothUtils1;
    private final Handler notifyHandler;
    int count = 0;
    private boolean mScanning;
    private Context context;

    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
            LogUtil.i("***deviceName-->" + device.getName() + "***deviceAddress-->"+device.getAddress());
            final BleAdvertisedData1 bData = BleUtil1.parseAdertisedData(scanRecord);
            String deviceName = device.getName();
            String reMac = device.getAddress();
            if (TextUtils.isEmpty(deviceName)) {
                deviceName = bData.getName();
            }
            boolean isBindMac = StringUtils1.isBindDevice(device.getAddress());
            if (isBindMac) {
                LogUtil.e("******当前已绑定MAC****isBindMac-->" + isBindMac + "****扫到的MAC-->" + reMac);
                scanCallDataBind(device, deviceName, scanRecord, rssi);
            } else {
                LogUtil.e("******当前没有绑定MAC-->" + isBindMac);
                scanCallDataNotBind(device, deviceName, scanRecord, rssi);
            }
        }
    };

    public BluetoothLeScanner(Handler nHandler, BluetoothUtils1 bluetoothUtils1, Context context) {
        mBluetoothUtils1 = bluetoothUtils1;
        notifyHandler = nHandler;
        this.context = context;
    }

    public boolean isScanning() {
        return mScanning;
    }

    @Override
    public void scanLeDevice(final int duration, final boolean enable) {
        LogUtil.e("mScanning:" + mScanning);
        if (enable) {
            //  mHandler.post(scanThread);
            if (mScanning) {
                return;
            }
            LogUtil.e("~ Starting Scan");
            // Stops scanning after a pre-defined scan period.
            if (duration > 0) {
                notifyHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("TAG", "~ Stopping Scan (timeout)");
                        mScanning = false;
                        if (null != mBluetoothUtils1 && null != mBluetoothUtils1.getBluetoothAdapter())
                            mBluetoothUtils1.getBluetoothAdapter().stopLeScan(mLeScanCallback);
                    }
                }, duration);
            }
            LogUtil.e("****BEGIN scan devices scanLeDevice****");
            mScanning = true;
            LogUtil.e("****mBluetoothUtils1***" + mBluetoothUtils1);
            if (null != mBluetoothUtils1 && null != mBluetoothUtils1.getBluetoothAdapter()) {
                LogUtil.e("*****扫描设备***");
                mBluetoothUtils1.getBluetoothAdapter().stopLeScan(mLeScanCallback);
                mBluetoothUtils1.getBluetoothAdapter().startLeScan(mLeScanCallback);
            }
        } else {
            LogUtil.e( "~ Stopping Scan");
            mScanning = false;
            if (null != mBluetoothUtils1 && null != mBluetoothUtils1.getBluetoothAdapter()) {
                mBluetoothUtils1.getBluetoothAdapter().stopLeScan(mLeScanCallback);
                // mHandler.removeCallbacks(scanThread);
            }
        }
    }

    @Override
    public void stopScan() {
        if (null != mBluetoothUtils1 && null != mBluetoothUtils1.getBluetoothAdapter()) {
            mBluetoothUtils1.getBluetoothAdapter().stopLeScan(mLeScanCallback);
            mScanning = false;
        }
    }

    /**
     * 对没有绑定MAC时的处理
     *
     * @param device
     * @param deviceName
     * @param scanRecord
     * @param rssi
     */
    private void scanCallDataNotBind(BluetoothDevice device, String deviceName, byte[] scanRecord, int rssi) {
        LogUtil.i("****扫到的蓝牙****deviceName-->" + device.getName() + "****deviceAddress-->"+device.getAddress());
        //if (!device.getAddress().startsWith("34:15:13") || (device.getName()!=null&&!device.getName().toLowerCase().equals("health scale"))) return;
        if (device != null && deviceName != null && deviceName.toLowerCase().equals("health scale") ||
                device != null && deviceName != null && deviceName.toLowerCase().equals("smart scale")) {
            LogUtil.e("*****发现合泰BLE称-->" + deviceName + "[" + device.getAddress() + "]");
            String deviceData = StringUtils.bytes2HexString(scanRecord);
            LogUtil.e("收到的广播数据111：" + deviceData);
            deviceData = StringUtils1.getReceiveScaleData(deviceData);
            if (deviceData != null && deviceData.equals("0000000000000000000000")) return;
            LogUtil.e("收到的广播数据：" + deviceData);
            final BluetoothLeDevice1 deviceLe = new BluetoothLeDevice1(device, rssi, scanRecord, System.currentTimeMillis(), deviceData);
            if (StringUtils1.isScaleData(deviceData)) {
                LogUtil.e("******脂肪秤***deviceData-->" + deviceData);
                if (StringUtils1.isLockData(deviceData)) {
                    count++;
                    LogUtil.e("****是广播锁定数据deviceData-->" + deviceData + "****count-->" + count);
                    if (count > 1) {
                        if (mScanning) {
                            if (null != mBluetoothUtils1 && null != mBluetoothUtils1.getBluetoothAdapter())
                                mBluetoothUtils1.getBluetoothAdapter().stopLeScan(mLeScanCallback);
                            mScanning = false;
                        }
                        if (null != notifyHandler) {
                            LogUtil.e("*****通知发现蓝牙了*****");
                            Message msg1 = notifyHandler.obtainMessage(BluetoolUtil1.FOUND_DEVICE);
                            msg1.obj = deviceLe;
                            notifyHandler.sendMessage(msg1);
                        }
                    } else {
                        if (null != notifyHandler) {
                            Message msg1 = notifyHandler.obtainMessage(BluetoolUtil1.GUANGBO_DATA);
                            msg1.obj = deviceLe;
                            notifyHandler.sendMessage(msg1);
                        }
                    }
                } else {
                    if (null != notifyHandler) {
                        Message msg1 = notifyHandler.obtainMessage(BluetoolUtil1.GUANGBO_DATA);
                        msg1.obj = deviceLe;
                        notifyHandler.sendMessage(msg1);
                    }
                }
            } else {
                if (deviceLe.getmRevicerData().startsWith("ca")) {
                    return;
                }
                if (mScanning) {
                    if (null != mBluetoothUtils1 && null != mBluetoothUtils1.getBluetoothAdapter())
                        mBluetoothUtils1.getBluetoothAdapter().stopLeScan(mLeScanCallback);
                    mScanning = false;
                }
                if (null != notifyHandler) {
                    LogUtil.e("*****通知发现蓝牙了*****");
                    Message msg1 = notifyHandler.obtainMessage(BluetoolUtil1.FOUND_DEVICE);
                    msg1.obj = deviceLe;
                    notifyHandler.sendMessage(msg1);
                }
            }
        } else if (device != null && deviceName != null && deviceName.toLowerCase().equals("electronic scale")) {
            LogUtil.e("****发现富晶方案秤-->" + deviceName + "[" + device.getAddress() + "]");
                 /* 停止蓝牙扫描 */
            if (mScanning) {
                if (null != mBluetoothUtils1 && null != mBluetoothUtils1.getBluetoothAdapter())
                    mBluetoothUtils1.getBluetoothAdapter().stopLeScan(mLeScanCallback);
                mScanning = false;
            }
            String deviceData = StringUtils.bytes2HexString(scanRecord);
            deviceData = StringUtils1.getReceiveScaleData(deviceData);
            LogUtil.e("收到的广播数据1：" + deviceData);
            final BluetoothLeDevice1 deviceLe = new BluetoothLeDevice1(device, rssi, scanRecord, System.currentTimeMillis(), null);
            if (null != notifyHandler) {
                LogUtil.e("*****通知发现蓝牙了******");
                count = 0;
                Message msg1 = notifyHandler.obtainMessage(BluetoolUtil1.FOUND_DEVICE);
                msg1.obj = deviceLe;
                notifyHandler.sendMessage(msg1);
            }
        } else if (device != null && deviceName != null && deviceName.equals(AppData.LF_SCALE)) {
            LogUtil.e("发现了巨威蓝牙方案秤:" + scanRecord);
            String deviceData = StringUtils.bytes2HexString(scanRecord);
            deviceData = StringUtils1.getReceverScaleData1(deviceData);
            if (deviceData != null && deviceData.equals("0000000000000000000000")) return;
            LogUtil.e("收到的广播数据：" + deviceData);
            final BluetoothLeDevice1 deviceLe = new BluetoothLeDevice1(device, rssi, scanRecord, System.currentTimeMillis(), deviceData);
            if (StringUtils1.isScaleData(deviceData)) {
                if (null != notifyHandler) {
                    Message msg1 = notifyHandler.obtainMessage(BluetoolUtil1.GUANGBO_DATA);
                    msg1.obj = deviceLe;
                    notifyHandler.sendMessage(msg1);
                }
            }
        }
    }

    /**
     * 有绑定MAC时的处理
     *
     * @param device
     * @param deviceName
     * @param scanRecord
     * @param rssi
     */
    private void scanCallDataBind(BluetoothDevice device, String deviceName, byte[] scanRecord, int rssi) {
        LogUtil.e("*****扫到的蓝牙-->" + deviceName+"***mac-->"+device.getAddress()+"***");
        if (device != null && deviceName != null && deviceName.toLowerCase().equals("health scale") ||
                device != null && deviceName != null && deviceName.toLowerCase().equals("smart scale")) {
            LogUtil.e("****发现合泰BLE称=" + deviceName + "[" + device.getAddress() + "]");
            String deviceData = "";
            if (scanRecord!=null && scanRecord.length>0){
                deviceData = StringUtils.bytes2HexString(scanRecord);
                LogUtil.i("收到的广播数据112：" + deviceData);
                deviceData = StringUtils1.getReceiveScaleData(deviceData);
                if (deviceData != null && deviceData.equals("0000000000000000000000")) return;
                LogUtil.e("收到的广播数据：" + deviceData);
            }
            final BluetoothLeDevice1 deviceLe = new BluetoothLeDevice1(device, rssi, scanRecord, System.currentTimeMillis(), deviceData);
            if (StringUtils1.isScaleData(deviceData)) {
                if (StringUtils1.isLockData(deviceData)) {
                    count++;
                    LogUtil.e("====是广播锁定数据1" + deviceData + "  count:" + count);
                    if (count > 1) {
                        if (mScanning) {
                            if (null != mBluetoothUtils1 && null != mBluetoothUtils1.getBluetoothAdapter())
                                mBluetoothUtils1.getBluetoothAdapter().stopLeScan(mLeScanCallback);
                            mScanning = false;
                        }
                        count = 0;
                        //通知发现蓝牙了
                        if (null != notifyHandler) {
                            Message msg1 = notifyHandler.obtainMessage(BluetoolUtil1.FOUND_DEVICE);
                            msg1.obj = deviceLe;
                            notifyHandler.sendMessage(msg1);
                        }
                    } else {
                        if (null != notifyHandler) {
                            Message msg1 = notifyHandler.obtainMessage(BluetoolUtil1.GUANGBO_DATA);
                            msg1.obj = deviceLe;
                            notifyHandler.sendMessage(msg1);
                        }
                    }
                } else {
                    if (null != notifyHandler) {
                        Message msg1 = notifyHandler.obtainMessage(BluetoolUtil1.GUANGBO_DATA);
                        msg1.obj = deviceLe;
                        notifyHandler.sendMessage(msg1);
                    }
                }
            } else {
                if (deviceLe.getmRevicerData().startsWith("ca")
                        /*|| (!TextUtils.isEmpty(deviceData)&&deviceData.equals("4865616c7468205363616c"))*/) {
                    return;
                }

                LogUtil.e("*****收到奇怪的数据deviceData-->"+deviceData);
                if (mScanning) {
                    if (null != mBluetoothUtils1 && null != mBluetoothUtils1.getBluetoothAdapter())
                        mBluetoothUtils1.getBluetoothAdapter().stopLeScan(mLeScanCallback);
                    mScanning = false;
                    LogUtil.e("*****停止扫描****");
                }

                if (null != notifyHandler) {
                    Message msg1 = notifyHandler.obtainMessage(BluetoolUtil1.FOUND_DEVICE);
                    msg1.obj = deviceLe;
                    LogUtil.e("*****通知发现蓝牙了*****");
                    notifyHandler.sendMessage(msg1);
                }
            }
        } else if (device != null && deviceName != null && deviceName.toLowerCase().equals("electronic scale")) {
            LogUtil.e("***发现富晶方案秤=" + deviceName + "[" + device.getAddress() + "]");
            //* 停止蓝牙扫描 *//*
            if (mScanning) {
                if (null != mBluetoothUtils1 && null != mBluetoothUtils1.getBluetoothAdapter())
                    mBluetoothUtils1.getBluetoothAdapter().stopLeScan(mLeScanCallback);
                mScanning = false;
            }
            String deviceData = StringUtils.bytes2HexString(scanRecord);
            deviceData = StringUtils1.getReceiveScaleData(deviceData);
            LogUtil.e("收到的广播数据1：" + deviceData);
            final BluetoothLeDevice1 deviceLe = new BluetoothLeDevice1(device, rssi, scanRecord, System.currentTimeMillis(), null);
            //通知发现蓝牙了
            if (null != notifyHandler) {
                Message msg1 = notifyHandler.obtainMessage(BluetoolUtil1.FOUND_DEVICE);
                msg1.obj = deviceLe;
                notifyHandler.sendMessage(msg1);
            }
        } else if (device != null && deviceName != null && deviceName.equals(AppData.LF_SCALE)) {
            LogUtil.e("发现了巨威蓝牙方案秤");
            String deviceData = StringUtils.bytes2HexString(scanRecord);
            deviceData = StringUtils1.getReceverScaleData1(deviceData);
            if (deviceData != null && deviceData.equals("0000000000000000000000")) return;
            LogUtil.e("收到的广播数据：" + deviceData);
            final BluetoothLeDevice1 deviceLe = new BluetoothLeDevice1(device, rssi, scanRecord, System.currentTimeMillis(), deviceData);
            if (StringUtils1.isScaleData(deviceData)) {
                if (null != notifyHandler) {
                    Message msg1 = notifyHandler.obtainMessage(BluetoolUtil1.GUANGBO_DATA);
                    msg1.obj = deviceLe;
                    notifyHandler.sendMessage(msg1);
                }
            }
        }
    }
}
